<?php
/**
 * tpshop
 * ============================================================================
 * * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
 * ============================================================================
 * 微信交互类
 */
namespace Home\Controller;
use Home\Logic\UsersLogic;

class LoginApiController extends BaseController {
    public $config;
    public $oauth;
    public $class_obj;

    public function __construct(){
        parent::__construct();
        $this->oauth = I('get.oauth');
        //获取配置
        $data = M('Plugin')->where("code='{$this->oauth}' and  type = 'login' ")->find();

        $this->config = unserialize($data['config_value']); // 配置反序列化

        if(!$this->oauth)
            $this->error('非法操作',U('User/login'));
        if($this->oauth!='weixin'){
            include_once  "plugins/login/{$this->oauth}/{$this->oauth}.class.php";
            $class = '\\'.$this->oauth; //
            $login = new $class($this->config); //实例化对应的登陆插件
            $this->class_obj = $login;
        }
    }


    public function wx_login(){
        $AppID ='wxb63cbe8ee2caa9f0';
        $AppSecret ='1b7b480b52de862acb9180b8ac55544e';

    $callback  =  'http://www.mattmatt.cn/Home/LoginApi/verify_wx_login/oauth/weixin/'; //回调地址
//微信登录 login.php
    session_start();
//-------生成唯一随机串防CSRF攻击
    $state1  = md5(uniqid(rand(), TRUE));
    $_SESSION["wx_state"]    =   $state1; //存到SESSION
//        $callback = urlencode($this->callback);
    $wxurl = "https://open.weixin.qq.com/connect/qrconnect?appid=".$AppID."&redirect_uri={$callback}&response_type=code&scope=snsapi_login&state=$state1#wechat_redirect";
    header("Location: $wxurl");
}



    public function verify_wx_login(){
//
//        dump($_GET['state']);
//        dump($_SESSION["wx_state"]);exit;
//
//        if($_GET['state']!=$_SESSION["wx_state"]){
//            exit("5001");
//        }

//        $wx_user = M('wx_user')->find();
//        $AppID =$wx_user['appid'];
//        $AppSecret =$wx_user['appsecret'];
        $AppID ='wxb63cbe8ee2caa9f0';
        $AppSecret ='1b7b480b52de862acb9180b8ac55544e';


        $url='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$AppID.'&secret='.$AppSecret.'&code='.$_GET['code'].'&grant_type=authorization_code';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_URL, $url);
        $json =  curl_exec($ch);
        curl_close($ch);
        $arr=json_decode($json,1);
//得到 access_token 与 openid
//        print_r($arr);
        $url='https://api.weixin.qq.com/sns/userinfo?access_token='.$arr['access_token'].'&openid='.$arr['openid'].'&lang=zh_CN';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_URL, $url);
        $json =  curl_exec($ch);
        curl_close($ch);
        $arr=json_decode($json,1);
        //  得到 用户资料
//        print_r($arr);

        $unionid =$arr['unionid'];
        $openid =$arr['openid'];
        $user_info=M('users')->where(array('unionid'=>$unionid))->find();
        $user_id=$user_info['user_id'];


        if($user_info){//已注册用户
//            dump($user_info);exit;
            //pc端 第一次登录的记录 openid
            if(empty($user_info['openid'])){
                $data['openid']=$openid;
                $res=M('users')->where(array('user_id'=>$user_id))->save($data);
            }
        }else{//未注册的
            //执行就数据操作

//            $add_data['openid']=$openid;
            $add_data['unionid']=$unionid;
            $add_data['nickname']=$arr['nickname'];
            $add_data['head_pic']=$arr['headimgurl'];
//            dump($add_data);exit;
            $user_id=M('users')->add($add_data);
            $user_info=M('users')->where(array('user_id'=>$user_id))->find();

            $nickname= $arr['nickname'];
            update_old_data($nickname,$user_id);

        }
        session('user',$user_info);
        setcookie('user_id',$user_id,null,'/');
        setcookie('is_distribut',$res['result']['is_distribut'],null,'/');
        $nickname = $user_info['nickname'];
        setcookie('uname',urlencode($nickname),null,'/');
        setcookie('cn',0,time()-3600,'/');
        $cartLogic = new \Home\Logic\CartLogic();
        $cartLogic->login_cart_handle($this->session_id,$res['result']['user_id']);  //用户登录后 需要对购物车
        $this->success('登录成功',U('Home/User/index'));












    }

    public function login(){

        if(!$this->oauth)
            $this->error('非法操作',U('User/login'));
        include_once  "plugins/login/{$this->oauth}/{$this->oauth}.class.php";
        $this->class_obj->login();
    }

    public function callback(){
        $data = $this->class_obj->respon();
        $logic = new UsersLogic();
        $data = $logic->thirdLogin($data);
        if($data['status'] != 1)
            $this->error($data['msg']);
        session('user',$data['result']);
        setcookie('user_id',$data['result']['user_id'],null,'/');
        setcookie('is_distribut',$data['result']['is_distribut'],null,'/');
        $nickname = empty($data['result']['nickname']) ? '第三方用户' : $data['result']['nickname'];
        setcookie('uname',urlencode($nickname),null,'/');
        setcookie('cn',0,time()-3600,'/');
        // 登录后将购物车的商品的 user_id 改为当前登录的id            
        M('cart')->where("session_id = '{$this->session_id}'")->save(array('user_id'=>$data['result']['user_id']));
        if(isMobile())
            $this->success('登陆成功',U('Mobile/User/index'));
        else
            $this->success('登陆成功',U('User/index'));
    }



    public function weixin_login(){
        $code = $_GET["code"];
        $appid = $this->config['appid'];
        $secret =$this->config['secret'];
        if (!empty($code))  //有code
        {
            //通过code获得 access_token + openid
            $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid
                . "&secret=" . $secret . "&code=" . $code . "&grant_type=authorization_code";
            $jsonResult = file_get_contents($url);
            $resultArray = json_decode($jsonResult, true);
            $access_token = $resultArray["access_token"];
            $openid = $resultArray["openid"];

            //通过access_token + openid 获得用户所有信息,结果全部存储在$infoArray里,后面再写自己的代码逻辑
            $infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid;
            $infoResult = file_get_contents($infoUrl);
            $infoArray = json_decode($infoResult, true);
            dump($infoArray);exit;





        }
    }
}